package com.sh.datasync.util;


import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.sh.datasync.model.CompareData;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;

/**
 * @Author: seeTools
 * @Date: 2025/6/21  8:41
 * @Version 1.0
 */
public class XmlUtils {

    private static final Logger logger = LoggerFactory.getLogger(XmlUtils.class);

    // 同步文件存储 文件夹
    static String[] FOLDERS = {"D://Eplan_integration/PLM2EPLAN/backup"};
    // 修改文件存储 文件夹
    static String MODIFY_FOLDER = "D://Eplan_integration/PLM2EPLAN/";
    // 备份文件夹
    static String BACK_UP_FOLDER = "D://Eplan_integration/PLM2EPLAN/oldData";
    // 获取最大文件数量
    static int MAX_FILE = 30;


    /**
     * 解析XML数据
     */
    public static void analysis() {
        // 遍历每个文件夹
        for (String folder : FOLDERS) {
            File dir = new File(folder);
            File[] files = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".xml") && !name.toLowerCase().contains("analysis"); // 只接受未处理的XML文件
                }
            });
            if (ArrayUtil.isNotEmpty(files)) {
                // 获取前30个或全部（如果不足30个）
                int count = Math.min(files.length, MAX_FILE);
                for (int i = 0; i < count; i++) {
                    File file = files[i];
                    String fileName = file.getName();
                    try {
                        // 1. 加载XML文件
                        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                        Document doc = dBuilder.parse(file);
                        doc.getDocumentElement().normalize(); // 使节点的值独立于它们的子节点，使其更容易处理
                        logger.info("Root element of the doc is " + doc.getDocumentElement().getNodeName());
                        // 日志文件路径
                        String logDir = "D://Eplan_integration/PLM2EPLAN/logs";
                        // 直接覆盖写入日志文件
                        com.sh.datasync.util.PlmFileScanner.scanAndWriteLog(file, "", logDir);
                        // 2.数据转换
                        convertData(doc);
                        // 3. 保存修改后的XML
                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
                        Transformer transformer = transformerFactory.newTransformer();
                        DOMSource source = new DOMSource(doc);
                        String[] strArray = fileName.split("_");
                        StreamResult result = new StreamResult(new File(MODIFY_FOLDER + strArray[0] + "_analysis_" + strArray[1]));
                        transformer.transform(source, result);
                        logger.info("XML文件修改完成并已保存");
                        // 4.备份数据
                        backUp(file);
                        // 5. 删除原xml
                        boolean isDeleted = file.delete();
                        if (isDeleted) {
                            logger.info(file.getName() + "XML文件删除成功");
                        } else {
                            logger.info(file.getName() + "XML文件删除失败");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                logger.info("No XML files found in " + folder);
            }
        }
    }


    /**
     * 数据转换
     *
     * @param doc
     */
    public static void convertData(Document doc) {
        // 2. 修改XML内容
        // 示例：修改所有PartProperty元素的值
        NodeList priceList = doc.getElementsByTagName("Properties");
        for (int i = 0;i < priceList.getLength();i++) {
            Element element  = (Element)priceList.item(i);
            NodeList childPriceList =  element.getElementsByTagName("PartProperty");

            // 1. 首先处理PropertyIndex="10"的停用标记
            Element propertyIndex10 = null;
            Element propertyIndex6 = null;
            
            // 找到PropertyIndex="10"和PropertyIndex="6"的元素
            for (int j = 0; j < childPriceList.getLength(); j++) {
                Element prop = (Element) childPriceList.item(j);
                String idx = prop.getAttribute("PropertyIndex");
                if ("10".equals(idx)) {
                    propertyIndex10 = prop;
                } else if ("6".equals(idx)) {
                    propertyIndex6 = prop;
                }
            }
            
            // 处理停用标记（只有存在PropertyIndex="10"时才处理）
            if (propertyIndex10 != null) {
                if (propertyIndex6 != null) {
                    String disabledFlag = propertyIndex10.getTextContent().trim();
                    if ("true".equalsIgnoreCase(disabledFlag)) {
                        // 在PropertyIndex="6"的部件名称后添加"（停用）"
                        String currentName = propertyIndex6.getTextContent();
                        if (!currentName.contains("（停用）")) {
                            propertyIndex6.setTextContent(currentName + "（停用）");
                        }
                    }
                }
                // 删除原来的PropertyIndex="10"节点
                element.removeChild(propertyIndex10);
            }

            // 2. 重新获取子节点列表（因为删除了一个节点）
            childPriceList = element.getElementsByTagName("PartProperty");
            
            // 大类 PropertyIndex = "3"
            Element element1 = null;
            //中类  PropertyIndex = "4"
            Element element2 = null;
            //小类  PropertyIndex = "5"
            Element element3 = null;
            
            // 重新查找PropertyIndex="3","4","5"的元素
            for (int j = 0; j < childPriceList.getLength(); j++) {
                Element prop = (Element) childPriceList.item(j);
                String idx = prop.getAttribute("PropertyIndex");
                if ("3".equals(idx)) {
                    element1 = prop;
                } else if ("4".equals(idx)) {
                    element2 = prop;
                } else if ("5".equals(idx)) {
                    element3 = prop;
                }
            }
            
            if (element1 != null && element2 != null && element3 != null) {
                String dlStr = StrUtil.toString(element1.getTextContent());
                String zlStr = StrUtil.toString(element2.getTextContent());
                String xlStr = StrUtil.toString(element3.getTextContent());
                // 表格数据
                List<CompareData> dataExcelList = ExcelUtils.analysis();
                // 初始化全部为空
                String textContent1 = "";
                String textContent2 = "";
                String textContent3 = "";
                
                // 遍历Excel数据，找到两个条件都匹配的行
                for (CompareData compareData : dataExcelList) {
                    // 两个条件必须同时满足：中类=XML中类 AND 小类=XML小类
                    if (compareData.getCategory2().equals(zlStr) && 
                        compareData.getCategory3().equals(xlStr)) {
                        
                        // 取Excel中的一类产品组（值）、产品组（值）、子产品组（值）
                        textContent1 = String.valueOf(compareData.getProductGroupValue1());
                        textContent2 = String.valueOf(compareData.getProductGroupValue2());
                        textContent3 = String.valueOf(compareData.getProductGroupValue3());
                        break; // 找到匹配行就跳出
                    }
                }
                String textContent = textContent1 + StrPool.SLASH + textContent2 +  StrPool.SLASH + textContent3;
                createDom(doc,element,textContent);
            }
        }
    }

    /**
     * 备份
     * @param file
     */
    public static void backUp(File file) {
        try {
            File destFile = new File(BACK_UP_FOLDER + "/" + file.getName());
            destFile.getParentFile().mkdirs();
            FileUtils.copyFile(file,destFile);
            logger.info("文件"+file.getName()+"备份成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建DOM
     * @param parentElement
     * @param textContent
     */
    public static void createDom (Document doc, Element parentElement , String textContent) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 5. 创建新的子标签
            Element childElement = doc.createElement("PartProperty");
            childElement.setAttribute("PropertyIndex", "10");
            childElement.setTextContent(textContent);
            parentElement.appendChild(childElement);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }
}
